$(function () {
    var defaultColunms = BaseTable.initColumn();
    var table = new BSTable(BaseTable.id, "/sys/role/list", defaultColunms);
    table.setPaginationType("server");
    BaseTable.table = table.init();
    init();
});

/**
 * 表格类容初始化
 */
var BaseTable = {
    id: "table",	//表格id
    seItem: null,		//选中的条目
    table: null,
};

/**
 * 初始化表格的列
 */
BaseTable.initColumn = function () {
    return [
        {field: 'selectItem',checkbox : true},
        {field: 'id',title : '序号',align: 'center', valign: 'middle',formatter : function(value, row, index) {return index+1;}},
        {title: 'id', field: 'id', visible: false, align: 'center', valign: 'middle'},
        {title: '角色ID', field: 'roleId', align: 'center', valign: 'middle', sortable: true},
        {title: '角色名称', field: 'roleName', align: 'center', valign: 'middle', sortable: true},
        {title: '备注', field: 'remark', align: 'center', valign: 'middle', sortable: true},
        {title: '创建时间', field: 'createTime', align: 'center', valign: 'middle', sortable: true},
        {title: '操作', field: 'status', align: 'center', valign: 'middle', sortable: true,formatter: function(value, row, index){
            var d = '<a class="btn btn-danger " href="#" onclick="remove('+row.roleId+')"><i class="fa fa-trash-o">删除</i></a>';
            var e = '&nbsp;&nbsp;&nbsp;&nbsp;';
            var f = '<a class="btn btn-primary " href="#" onclick="getInfo(' + row.roleId + ')"><i class="fa fa-pencil-square-o">详情</i>';
            return d+e+f;
        }}
    ];
};

/**
 * 检查是否选中
 */
BaseTable.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        alert("请先选中表格中的某一记录！");
        return false;
    } else {
        BaseTable.seItem = selected[0];
        return true;
    }
};

/**
 * 查询表格列表
 */
BaseTable.search = function () {
    var queryData = {};
    queryData['roleName'] = $("#roleName").val();
    BaseTable.table.refresh({query: queryData});
};

function remove(id) {
    var ids = new Array();
    ids.push(id);
    ajaxSubmit("/sys/role/delete", JSON.stringify(ids), function (r) {
        if (r.code === 0) {
            showSuccessMsg("操作成功！",function () {
                reloadPage();
            });
        } else {
            alert(r.msg);
        }
    })
}

function clearInput(obj) {
    $(obj).prev().val('');
}

function getInfo(id) {
    vm.getMenuTree(id);
    vm.showList = false;
}


//菜单树
var menu_ztree;
var menu_setting = {
	data: {
		simpleData: {
			enable: true,
			idKey: "menuId",
			pIdKey: "parentId",
			rootPId: -1
		},
		key: {
			url:"nourl"
		}
	},
	check:{
		enable:true,
		nocheckInherit:true
	}
};

var vm = new Vue({
	el:'#app',
	data:{
		showList: true,
		data:{},
        roleName:''
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.data = {};
			vm.getMenuTree(null);
		},
		update: function () {
			var roleId = getSelectedRow();
			if(roleId == null){
				return ;
			}
			
			vm.showList = false;
            vm.getMenuTree(roleId);

		},
		del: function () {
            //获取选中的列
            var ids = getSelections('table', 'roleId');
            if (ids.length == 0) {
                alert('请选择需要删除的数据！');
                return;
            }
            console.info(ids);
            showWarningMsg('确定要删除选中的记录？',function () {
                ajaxSubmit('/sys/role/delete',JSON.stringify(ids),function (r) {
                    if(r.code == 0){
                        showSuccessMsg('操作成功!');
                        vm.reload();
                    }else{
                        alert(r.msg);
                    }
                })
            })
		},
		getRole: function(roleId){
            $.get(baseURL + "sys/role/info/"+roleId, function(r){
            	vm.data = r.role;
                vm.roleName = vm.data.roleName;
                //勾选角色所拥有的菜单
    			var menuIds = vm.data.menuIdList;
    			for(var i=0; i<menuIds.length; i++) {
    				var node = menu_ztree.getNodeByParam("menuId", menuIds[i]);
    				menu_ztree.checkNode(node, true, false);
    			}

    		});
		},
		saveOrUpdate: function () {
			//获取选择的菜单
			var nodes = menu_ztree.getCheckedNodes(true);
			var menuIdList = new Array();
			for(var i=0; i<nodes.length; i++) {
				menuIdList.push(nodes[i].menuId);
			}
			vm.data.menuIdList = menuIdList;


			var url = vm.data.roleId == null ? "sys/role/save" : "sys/role/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.data),
			    success: function(r){
			    	if(r.code === 0){
						showSuccessMsg('操作成功', function(){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		getMenuTree: function(roleId) {
			//加载菜单树
			$.get(baseURL + "sys/menu/list", function(r){
				menu_ztree = $.fn.zTree.init($("#menuTree"), menu_setting, r);
				//展开所有节点
				menu_ztree.expandAll(true);
				
				if(roleId != null){
					vm.getRole(roleId);
				}
			});
	    },
	    reload: function () {
            resetForm();
            vm.showList = true;
            BaseTable.search();
		}
	}
});

function init() {
    $("#Form")
        .bootstrapValidator(
            {
                errorElement: 'span',
                errorClass: 'help-block',
                fields: {
                    roleName: {
                        validators: {
                            notEmpty: {
                                message: '该项目不能为空'
                            },
                            stringLength: {
                                max: 10,
                                message: '账号长度不能超过10个单位'
                            },
                            remote: {
                                message: '该角色已存在',
                                url: '/sys/role/checkRoleName',
                                data: function(validator) {
                                    if (vm.data!=null && vm.roleName == $('[name="roleName"]').val()) {
                                        return false;
                                    }
                                    return {
                                        roleName: vm.data.roleName,
                                    };
                                },
                                delay: 3000
                            }
                        }
                    },
                    remark:{
                        validators : {
                            stringLength : {
                                max : 200,
                                message : '最大长度不能超过200位'
                            }
                        }
                    },
                }
            }).on('success.form.bv', function (e) {
        e.preventDefault();
        vm.saveOrUpdate();
        return false;
    });
}